package com.central.modules.sys.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.central.common.annotation.LogOperation;
import com.central.common.exception.BizExceptionEnum;
import com.central.common.page.PageData;
import com.central.common.utils.ConvertUtils;
import com.central.common.utils.Result;
import com.central.common.validator.ValidatorUtils;
import com.central.common.validator.group.AddGroup;
import com.central.common.validator.group.DefaultGroup;
import com.central.common.validator.group.UpdateGroup;
import com.central.modules.security.password.PasswordUtils;
import com.central.modules.security.user.SecurityUser;
import com.central.modules.security.user.UserDetail;
import com.central.modules.sys.dto.SysRolePageVo;
import com.central.modules.sys.dto.SysUserDTO;
import com.central.modules.sys.entity.SysUserEntity;
import com.central.modules.sys.model.AddSysUserRequest;
import com.central.modules.sys.model.SetRolesToUserRequest;
import com.central.modules.sys.model.SysUserQueryBean;
import com.central.modules.sys.model.UpdatePwdRequest;
import com.central.modules.sys.service.SysRoleService;
import com.central.modules.sys.service.SysRoleUserService;
import com.central.modules.sys.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户管理
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/sys_user")
public class SysUserController {

    private final SysUserService sysUserService;
    private final SysRoleService sysRoleService;
    private final SysRoleUserService roleUserService;

    @GetMapping("/page_for_other")
    public Result<PageData<SysUserDTO>> pageForOther(SysUserQueryBean queryBean) {
        IPage<SysUserEntity> page = sysUserService.pageSearch(queryBean);
        return Result.succeed(PageData.copy(page, page.getRecords().stream().map(e -> {
            SysUserDTO sysUserDTO = new SysUserDTO();
            sysUserDTO.setRealName(e.getRealName());
            sysUserDTO.setMobile(e.getMobile());
            sysUserDTO.setId(e.getId());
            return sysUserDTO;
        }).collect(Collectors.toList())));
    }
    @GetMapping("/page")
    public Result<PageData<SysUserDTO>> page(SysUserQueryBean queryBean) {
        IPage<SysUserEntity> page = sysUserService.pageSearch(queryBean);
        return Result.succeed(PageData.copy(page, page.getRecords().stream().map(e -> {
            SysUserDTO sysUserDTO = new SysUserDTO();
            BeanUtils.copyProperties(e, sysUserDTO);
            return sysUserDTO;
        }).collect(Collectors.toList())));
    }

    @GetMapping("/detail/{userId}")
    public Result<SysUserDTO> get(@PathVariable("userId") Long userId) {
        SysUserEntity data = sysUserService.getDetailById(userId);
        SysUserDTO sysUserDTO=  ConvertUtils.sourceToTarget(data, SysUserDTO.class);
        sysUserDTO.setRoles(sysRoleService.findAllByIds(roleUserService.listAllByUserId(data.getId())).stream().map(e -> {
            SysRolePageVo sysRolePageVo = new SysRolePageVo();
            BeanUtils.copyProperties(e, sysRolePageVo);
            return sysRolePageVo;
        }).collect(Collectors.toList()));
        return Result.succeed(sysUserDTO);
    }


    @PutMapping("/password")
    @LogOperation("修改密码")
    public Result<Void> password(@RequestBody UpdatePwdRequest dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto);

        UserDetail user = SecurityUser.getUser();

        //原密码不正确
        if (!PasswordUtils.matches(dto.getPassword(), user.getPassword())) {
            return Result.failed(BizExceptionEnum.PASSWORD_ERROR);
        }

        sysUserService.updatePassword(user.getId(), dto.getNewPassword());

        return Result.succeed(null);
    }

    @PutMapping("/reset_pwd/{userId}")
    @LogOperation("重置密码")
    public Result<Void> resetPwd(@PathVariable Long userId) {

        sysUserService.updatePassword(userId, "123456");
        return Result.succeed(null);
    }

    @PutMapping("/update_status")
    @LogOperation("修改状态")
    public Result<Void> updateStatus(@RequestBody Map<String, Object> reqMap) {
        Long userId = MapUtil.getLong(reqMap, "userId");
        Integer status = MapUtil.getInt(reqMap, "status");
        sysUserService.updateStatus(userId, status);
        return Result.succeed(null);
    }

    @PostMapping("/add")
    @LogOperation("保存")
    public Result<Void> save(@RequestBody AddSysUserRequest request) {
        //效验数据
        ValidatorUtils.validateEntity(request, AddGroup.class, DefaultGroup.class);

        //检查是否唯一
        SysUserEntity sysUserEntity = sysUserService.getByUsername(request.getMobile());
        if (Objects.nonNull(sysUserEntity)) {
            return Result.failed(BizExceptionEnum.USERNAME_EXIT);
        }
        sysUserService.add(request);

        return Result.succeed(null);
    }

    @PutMapping("/update")
    @LogOperation("修改")
    public Result<Void> update(@RequestBody AddSysUserRequest request) {
        //效验数据
        request.setMobile(null);
        ValidatorUtils.validateEntity(request, UpdateGroup.class, DefaultGroup.class);
        sysUserService.updateById(request.getId(), request);
        return Result.succeed(null);
    }

    @DeleteMapping("/del")
    @LogOperation("删除")
    @RequiresPermissions("sys:user:delete")
    public Result<Void> delete(@RequestBody Long[] ids) {
        //效验数据
        sysUserService.delete(ids);
        for (Long id : ids) {
            roleUserService.cleanByUserId(id);
        }
        return Result.succeed(null);
    }

    //当前人信息
    @GetMapping("/curInfo")
    public Result<SysUserDTO> info(@RequestParam(required = false, defaultValue = "true") Boolean includeAll) {
        SysUserDTO data = ConvertUtils.sourceToTarget(SecurityUser.getUser(), SysUserDTO.class);
        if (includeAll) {
            data.setRoles(sysRoleService.findAllByIds(roleUserService.listAllByUserId(data.getId())).stream().map(e -> {
                SysRolePageVo sysRolePageVo = new SysRolePageVo();
                BeanUtils.copyProperties(e, sysRolePageVo);
                return sysRolePageVo;
            }).collect(Collectors.toList()));
        }
        return Result.succeed(data);
    }

    //修改自己信息
    @PutMapping("/update_info")
    public Result<Void> updateInfo(@RequestBody AddSysUserRequest request) {
        sysUserService.updateById(SecurityUser.getUserId(), request);
        return Result.succeed(null);
    }


    //分配角色
    @PostMapping("/set_role")
    public Result<Void> setMenuIds(@RequestBody SetRolesToUserRequest request) {
        ValidatorUtils.validateEntity(request, DefaultGroup.class);
        roleUserService.add(request.getUserId(), request.getRoleIds());
        return Result.succeed(null);
    }

}